package cc.linker.steplink.crm.service;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.support.oauth.OauthProperties;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class OauthCheckService {

    @Autowired
    private OauthProperties oauthProperties;

    @Autowired
    private HttpService httpService;

    public Boolean checkOauth(String token){
        try {
            String clientId = oauthProperties.getClientId();
            String clientSecret = oauthProperties.getClientSecret();
            //base64加密（clientId:clientSecret）
            Base64 base64 = new Base64();
            String text = clientId+":"+clientSecret;
            byte[] textByte;
            textByte = text.getBytes("UTF-8");
            String encodedText = base64.encodeToString(textByte);
            Map headers = new HashMap();
            headers.put("Authorization", "Basic "+encodedText);
            String clientAddress =oauthProperties.getServerUrl();
            Map list = new HashMap();
            list.put("token",token);
            list.put("token_type_hint","access_token");
            String result = httpService.doPost(clientAddress+"introspect", list ,headers);
            if("".equals(result) || result == null){
                throw GlobalException.build("OAuth服务未返回数据！");
            }
            //创建json解析器
            JsonParser parser=new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            if(object.get("active")!=null){
                String active = object.get("active").toString();
                if("0".equals(active) || "".equals(active)){
                    throw GlobalException.build("token未激活或已过期，请传正确的token！");
                }else {
                    return true;
                }
            }else {
                throw GlobalException.build("token未激活或已过期，请传正确的token！");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw GlobalException.build("OAuth服务请求异常！");
        }
    }
}
